<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\repair\model;

use app\admin\model\RouteModel;
use think\Model;
use think\Db;
use tree\Tree;

class RepairCategoryModel extends Model
{

    protected $type = [
        'more' => 'array',
    ];

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    /**
     * 分类名敏感词过滤
     * @param $value
     * @return false|int
     */
    public function setNameAttr($value)
    {
        return cmf_replaceSensitive($value);
    }

    /**
     * 标题敏感词过滤
     * @param $value
     * @return false|int
     */
    public function setTitleAttr($value)
    {
        return cmf_replaceSensitive($value);
    }

    public function setPageTitleAttr($value)
    {
        return cmf_replaceSensitive($value);
    }

    public function setPageKeywordsAttr($value)
    {
        return cmf_replaceSensitive($value);
    }

    public function setPageDescriptionAttr($value)
    {
        return cmf_replaceSensitive($value);
    }

    /**
     * post_content 自动转化
     * @param $value
     * @return string
     */
    public function getDescriptionAttr($value)
    {
        $value = cmf_replaceSensitive($value);

        return cmf_replace_content_file_url(htmlspecialchars_decode($value));
    }

    /**
     * post_content 自动转化
     * @param $value
     * @return string
     */
    public function setDescriptionAttr($value)
    {
        return htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($value), true));
    }

    /**
     * post_content 自动转化
     * @param $value
     * @return string
     */
    public function getContentAttr($value)
    {
        return htmlspecialchars_decode($value);
    }

    /**
     * post_content 自动转化
     * @param $value
     * @return string
     */
    public function setContentAttr($value)
    {
        return htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($value), true));
    }

     /**
     * 生成分类 select树形结构
     * @param int $selectId     需要选中的分类 id
     * @param int $currentCid   需要隐藏的分类 id
     * @param int $optionId     可操作的分类 id
     * @param int $isAudit      是否禁用不需要审核流程的分类
     * @return string
     */
    public function adminCategoryTree($selectId = 0, $currentCid = 0, $optionId = '', $isAudit=0)
    {
        $where = [
            'delete_time' => 0,
            'site_id'     => get_site_id(),
        ];

        //需要隐藏的分类id,不进行该id查询
        if (!empty($currentCid)) {
            $where['id'] = ['neq', $currentCid];
        }

        $categories = $this->order("list_order ASC")->where($where)->select()->toArray();

        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;';

        $roleId = session('ROLE_ID');   //当前角色ID

        $newCategories = [];
        foreach ($categories as $item) {
            //需要选中的分类 id
            $item['selected'] = $selectId == $item['id'] ? "selected" : "";

            $disabled = 0;

            //把不需要审核流程的分类设为禁止选择
            if( $isAudit && $item['audit_id'] == 0 ){
                $disabled = 1;
            }

            //若仍可选择，则进行分类栏目权限判断；若无权限，则设为禁止选择
            if( $roleId != 1 ){
                if( $disabled != 1 ){
                    if( !empty($optionId) ){
                        if( !in_array($item['id'], $optionId) ){
                            $disabled = 1;
                        }
                    }else{
                        if( is_array($optionId) ){
                            $disabled = 1;
                        }
                    }
                }
            }

            // 是否设为禁止选择
            $item['disabled'] = $disabled == 1 ? "disabled style='background:#ccc;' " : "";

            array_push($newCategories, $item);
        }

        $tree->init($newCategories);
        $str     = '<option value=\"{$id}\" {$selected} {$disabled}>{$spacer}{$name}</option>';
        $treeStr = $tree->getTree(0, $str);

        return $treeStr;
    }

    /**
     * @param int|array $currentIds
     * @param string $tpl
     * @return string
     */
    public function adminCategoryTableTree($currentIds = 0, $tpl = '', $idList = [])
    {   
        $where = [
            'delete_time' => 0,
            'site_id'     => get_site_id(),
        ];
       
        $categories = $this->order("list_order ASC")->where($where)->select()->toArray();

        $tree       = new Tree();
        $tree->icon = ['&nbsp;&nbsp;&nbsp;│', '&nbsp;&nbsp;&nbsp;├─', '&nbsp;&nbsp;&nbsp;└─'];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        if (!is_array($currentIds)) {
            $currentIds = [$currentIds];
        }

        $isAdd    = cmf_auth_check(cmf_get_current_admin_id(), 'repair/AdminCategory/add');
        $isEdit   = cmf_auth_check(cmf_get_current_admin_id(), 'repair/AdminCategory/edit');
        $isDelete = cmf_auth_check(cmf_get_current_admin_id(), 'repair/AdminCategory/delete');

        $roleId   = session('ROLE_ID');   //当前角色ID

        $newCategories = [];
        foreach ($categories as $item) {
            $item['disabled'] = '';

            if( $roleId != 1 ){
                if( !empty($idList) ){
                    if( !in_array($item['id'], $idList) ){
                        $item['disabled'] = 'disabled';
                    }
                }
            }
            
            $item['checked']    = in_array($item['id'], $currentIds) ? 'checked' : '';
            $item['url']        = cmf_url('repair/List/index', ['id' => $item['id']]);
            
            $item['str_action'] = '';
            if( $isAdd == 1 ){
                $item['str_action'].= '<a class="layui-btn layui-btn-normal layui-btn-xs" href="' . url("AdminCategory/add", ["parent" => $item['id']]) . '">添加子分类</a> ';
            }
            if( $isEdit == 1 ){
                $item['str_action'].= '<a class="layui-btn layui-btn-xs" href="' . url("AdminCategory/edit", ["id" => $item['id']]) . '">' . lang('EDIT') . '</a> ';
            }
            if( $isDelete == 1 ){
                $item['str_action'].= '<a class="layui-btn layui-btn-danger layui-btn-xs js-ajax-delete" href="' . url("AdminCategory/delete", ["id" => $item['id']]) . '">' . lang('DELETE') . '</a> ';
            }

            // 是否显示(是否发布)
            $item['display'] = '<span class="layui-btn layui-btn-xs layui-btn-danger">'.lang('HIDE').'</span>';
            if( $item['is_show'] == 1 ){
                $item['display'] = '<span class="layui-btn layui-btn-normal layui-btn-xs">'.lang('DISPLAY').'</span>';

            }

            $item['create_time'] = date('Y/m/d H:i:s',$item['create_time']);

            array_push($newCategories, $item);
        }

        $tree->init($newCategories);

        if (empty($tpl)) {
            // $tpl = "<tr>
            //             <td><input name='list_orders[\$id]' type='text' size='3' value='\$list_order' class='input-order'></td>
            //             <td>\$id</td>
            //             <td>\$spacer <a href='\$url' target='_blank'>\$name</a></td>
            //             <td>\$description</td>
            //             <td>\$str_action</td>
            //         </tr>";

            $tpl = "<tr>
                        <td><input name='list_orders[\$id]' type='text' size='3' value='\$list_order' class='input-order'></td>
                        <td>\$id</td>
                        <td>\$spacer <a href='\$url' target='_blank'>\$name</a></td>
                        <td>\$display</td>
                        <td>\$create_time</td>
                        <td>\$str_action</td>
                    </tr>";
        }
        $treeStr = $tree->getTree(0, $tpl);

        return $treeStr;
    }

    /**
     * 添加文章分类
     * @param $data
     * @return bool
     */
    public function addCategory($data)
    {
        $result = true;
        self::startTrans();
        try {
            if (!empty($data['more']['thumbnail'])) {
                $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
            }

            //站点ID
            $data['site_id'] = get_site_id();
            
            $this->allowField(true)->save($data);
            $id = $this->id;
            if (empty($data['parent_id'])) {

                $this->where( ['id' => $id])->update(['path' => '0-' . $id]);
            } else {
                $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
                $this->where( ['id' => $id])->update(['path' => "$parentPath-$id"]);

            }
            self::commit();
        } catch (\Exception $e) {
            self::rollback();
            $result = false;
        }

        if ($result != false) {
            //设置别名
            $routeModel = new RouteModel();
            if (!empty($data['alias']) && !empty($id)) {
                $routeModel->setRoute($data['alias'], 'repair/List/index', ['id' => $id], 2, 5000);
                $routeModel->setRoute($data['alias'] . '/:id', 'repair/Article/index', ['cid' => $id], 2, 4999);
            }
            $routeModel->getRoutes(true);
        }

        return $result;
    }

    public function editCategory($data)
    {
        $result = true;

        $id          = intval($data['id']);
        $parentId    = intval($data['parent_id']);
        $oldCategory = $this->where('id', $id)->find();

        if (empty($parentId)) {
            $newPath = '0-' . $id;
        } else {
            $parentPath = $this->where('id', intval($data['parent_id']))->value('path');
            if ($parentPath === false) {
                $newPath = false;
            } else {
                $newPath = "$parentPath-$id";
            }
        }

        if (empty($oldCategory) || empty($newPath)) {
            $result = false;
        } else {


            $data['path'] = $newPath;
            if (!empty($data['more']['thumbnail'])) {
                $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
            }
            // if( !empty($data['post_content']) ){
            //     $data['post_content'] =
            // }

            $data['is_show'] = isset($data['is_show']) ? $data['is_show'] : 1;
            $this->isUpdate(true)->allowField(true)->save($data, ['id' => $id]);

            $children = $this->field('id,path')->where('path', 'like', "%-$id-%")->select();

            if (!empty($children)) {
                foreach ($children as $child) {
                    $childPath = str_replace($oldCategory['path'] . '-', $newPath . '-', $child['path']);
                    $this->isUpdate(true)->save(['path' => $childPath], ['id' => $child['id']]);
                }
            }

            $routeModel = new RouteModel();
            if (!empty($data['alias'])) {
                $routeModel->setRoute($data['alias'], 'repair/List/index', ['id' => $data['id']], 2, 5000);
                $routeModel->setRoute($data['alias'] . '/:id', 'repair/Article/index', ['cid' => $data['id']], 2, 4999);
            } else {
                $routeModel->deleteRoute('repair/List/index', ['id' => $data['id']]);
                $routeModel->deleteRoute('repair/Article/index', ['cid' => $data['id']]);
            }

            $routeModel->getRoutes(true);
        }


        return $result;
    }

    // public function getThumbSize($term_id){
    //     $thumb_size = '';
    //     if( empty($term_id) ) return $thumb_size;
        
    //     // $data = M('Terms')->field('parent,thumb_size')->find($term_id);
    //     $data = Db::name('RepairCategory')->field('parent_id,thumb_size')->find($term_id);
    //     if( !empty($data) ){
    //         if( empty($data['thumb_size']) ){
    //             $thumb_size = $this->getThumbSize($data['parent_id']);
    //         }else {
    //             $thumb_size = $data['thumb_size'];
    //         }
    //     }

    //     return $thumb_size;
    // }

}
